package com.hahaliu.hahaliu.service.impl.video;

import com.hahaliu.hahaliu.common.exception.BaseException;
import com.hahaliu.hahaliu.common.utils.MinioUtil;
import com.hahaliu.hahaliu.common.context.CurrentUser;
import com.hahaliu.hahaliu.common.utils.RedisUtil;
import com.hahaliu.hahaliu.mapper.VideoMapper;
import com.hahaliu.hahaliu.pojo.dto.VideoUploadDTO;
import com.hahaliu.hahaliu.pojo.entity.Video;
import com.hahaliu.hahaliu.service.video.VideoUploadService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.time.LocalDateTime;
import java.util.Objects;
import java.util.UUID;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.Executor;

@Service
@Slf4j
public class VideoUploadServiceImpl implements VideoUploadService {
	@Autowired
	private MinioUtil minioUtil;
	@Autowired
	private VideoMapper videoMapper;
	@Autowired
	private CurrentUser currentUser;
	@Autowired
	private RedisUtil redisUtil;
	@Autowired
	@Qualifier("taskExecutor")
	private Executor taskExecutor;

	public int askCurrentChunk(String hash) {
		// 查询minio当前存在的分片数量，即前端要上传的分片序号
        return minioUtil.countFiles("chunk", hash + "-");
	}

	public void uploadChunk(MultipartFile chunk, String hash, Integer index) {
		// 构建分片文件名
		String chunkFileName = hash + "-" + index;

		// 存储到minio
		try {
            minioUtil.upload(chunk,"chunk", chunkFileName);
        } catch (Exception e) {
            log.error("上传分片文件时出错了");
			throw new BaseException("上传分片文件时出错了");
        }
	}

	public void cancelUpload(String hash) {
		// 删除minio上的分片文件
        minioUtil.deleteFiles("chunk", hash + "-");
	}
	public void addVideo(VideoUploadDTO videoUploadDTO) {
		if (videoUploadDTO.getTitle().trim().isEmpty()) {
			throw new BaseException("标题不能为空");
		}
		if (videoUploadDTO.getTitle().length() > 80) {
			throw new BaseException("标题不能超过80字");
		}
		if (videoUploadDTO.getDescription().length() > 2000) {
			throw new BaseException("简介太长啦");
		}

		// 合并分片并获取视频的访问地址
		String videoUrl = minioUtil.mergeChunks(videoUploadDTO.getHash());

		Video video = new Video();

		// 对象属性拷贝
//		BeanUtils.copyProperties(videoUploadDTO, video);
		// 设置视频访问地址
		video.setVideoUrl(videoUrl);
		video.setTitle(videoUploadDTO.getTitle());
		video.setCoverUrl(videoUploadDTO.getCoverUrl());
		video.setDescription(
				Objects.equals(videoUploadDTO.getDescription(), "") ?
						"-" :
						videoUploadDTO.getDescription()
		);
		video.setMcId(videoUploadDTO.getMcId());
		video.setScId(videoUploadDTO.getScId());
		video.setType(videoUploadDTO.getType());
		video.setAuth(videoUploadDTO.getAuth());
		Integer uId = currentUser.getUserId();
		video.setDuration(videoUploadDTO.getDuration());
		video.setUId(uId);
		video.setPlay(0); // 播放数
		video.setTags(videoUploadDTO.getTags());
		// 设置状态审核中
		video.setStatus(0);
		video.setDanmu(0);
		video.setGood(0);
		video.setBad(0);
		video.setCoin(0);
		video.setCollect(0);
		video.setComment(0);
		video.setUploadDate(LocalDateTime.now());

		videoMapper.insert(video);

		CompletableFuture.runAsync(() -> redisUtil.setExObjectValue("video:" + video.getVId(), video), taskExecutor);
		CompletableFuture.runAsync(() -> redisUtil.addMember("video_status:0", video.getVId()), taskExecutor);
		CompletableFuture.runAsync(() -> redisUtil.setExObjectValue("videoStats:" + video.getVId(), video), taskExecutor);
	}
	

}
